package vip.sone.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.realm.Realm;

/**
 * 实现Realm接口用于认证用户
 *
 * 继承AuthorizingRealm实现用Realm进行授权
 */
public class MyRealm1 implements Realm {
    @Override
    public String getName() {
        return "myrealm1";
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        // 仅支持用户名密码Token
        return token instanceof UsernamePasswordToken;
    }

    /**
     * 返回认证信息
     */
    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 得到用户名和密码 只有基于用户名和密码认证的Token可以这样
        String username = (String) token.getPrincipal();
        // 注意这里的强转
        String password = new String((char[])token.getCredentials());
        if (!"zhang".equals(username)) {
            throw new UnknownAccountException();
        }
        if (!"123".equals(password)) {
            throw new IncorrectCredentialsException();
        }
        // 认证成功就返回一个AuthenticationInfo实现
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
